from rich.console import Console
from rich.prompt import Prompt
from rich.panel import Panel
from rich.tree import Tree
import os

console = Console()

def build_tree(path, tree_node):
    for item in sorted(os.listdir(path)):
        full_path = os.path.join(path, item)
        if os.path.isdir(full_path):
            node = tree_node.add(item + "/")
            build_tree(full_path, node)
        else:
            tree_node.add(item)

def file_browser():
    root = Tree("📁 根目录", guide_style="bold blue")
    build_tree(".", root)
    
    while True:
        console.print(Panel.fit(root, title="文件浏览器"))
        action = Prompt.ask(
            "[green]操作:[/green] [bold red]q[/bold red]退出 [bold green]s[/bold green]搜索 [bold blue]cd[/bold blue]切换目录",
            choices=["q", "s", "cd"],
            default="q"
        )
        if action == "cd":
            target = Prompt.ask("输入目标路径")
            if os.path.exists(target):
                root = Tree("📁 根目录", guide_style="bold blue")
                build_tree(target, root)
            else:
                console.print("[bold red]路径不存在[/]")
        elif action == "s":
            keyword = Prompt.ask("输入搜索关键词")
            # 实现搜索逻辑（此处为简化示例）
            console.print(f"[yellow]搜索功能待实现: {keyword}[/]")

file_browser()